package com.example.mqttledmenu;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.ListFragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class FragmentSubscribe extends ListFragment {
    private static final String ARG_PARAM1 = "param1";
    private String mParam1;
    private View rootView;
    private ListView lv;
    private SimpleAdapter adapter;
    private ArrayList<SubscribeItem> apartmentList = new ArrayList<>();

    public FragmentSubscribe() {

    }

    public static FragmentSubscribe newInstance(String param1, String param2) {
        FragmentSubscribe fragment = new FragmentSubscribe();
        Bundle args = new Bundle();//页面信息传输
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    public void getDepartmentList() {
        apartmentList = new ArrayList<>();//清空数据
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Config.serverUrl).build();
        UploadService uploadService = retrofit.create(UploadService.class);
        Call<ResponseBody> call = uploadService.getPlate(Config.getInstance().getUserId());//与后端约定，不传入id直接获取全部
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String result = null;
                try {
                    result = response.body().string();
                    JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                    if (!returnData.get("code").toString().equals("200")) {
                        Toast.makeText(getActivity(), "服务端错误~", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    try {
                        JSONArray myjsonArray = new JSONArray(returnData.get("data").toString());
                        for (int i = 0; i < myjsonArray.length(); i++) {
                            JSONObject jsonObject = myjsonArray.getJSONObject(i);
                            apartmentList.add(new SubscribeItem(jsonObject.get("icon").toString(),
                                    jsonObject.get("department").toString(), jsonObject.get("departmentId").toString(), jsonObject.get("isSubscribe").toString().equals("1")));
                        }
                        adapter = new SimpleAdapter(getActivity(), getData(apartmentList),
                                R.layout.setting_adapter_item, new String[]{"avatar", "department", "right_icon"},
                                new int[]{R.id.image, R.id.name, R.id.right_icon});
                        //设置glide占位符
                        RequestOptions requestOptions = new RequestOptions()
                                .placeholder(R.drawable.loading)
                                .error(R.drawable.unknow_person)
                                .fallback(R.drawable.unknow_person);
                        //设置头像切换效果(其实比较耗性能)
                        DrawableCrossFadeFactory factory = new DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build();
                        adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
                            @Override
                            public boolean setViewValue(View view, Object data, String textRepresentation) {
                                if (view.getId() == R.id.image) {
                                    ImageView iv = (ImageView) view;
                                    Glide.with(FragmentSubscribe.this)
                                            .load(data.toString())
                                            .apply(requestOptions)
                                            .transition(DrawableTransitionOptions.with(factory)).transform(new CircleCrop()).into(iv);
                                    return true;
                                }
                                return false;
                            }
                        });
                        setListAdapter(adapter);
                    } catch (JSONException e) {
                        Log.d("nightowl", "onResponse: yichang");
                        e.printStackTrace();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }
        getDepartmentList();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_subscribe, container, false);
        }
        initView();
        return rootView;
    }

    private void initView() {
        lv = rootView.findViewById(android.R.id.list);
    }

    public void onListItemClick(ListView l, View v, int position, long id) {
        //订阅或者取消订阅部门
        SubscribeItem temp = apartmentList.get(position);
        if (temp.isSubScribe) {
            //取消订阅
            Retrofit retrofit = new Retrofit.Builder().baseUrl(Config.serverUrl).build();
            UploadService uploadService = retrofit.create(UploadService.class);
            Call<ResponseBody> call = uploadService.unsubscribe(Config.getInstance().getUserId(), temp.department_id);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    String result = null;
                    try {
                        result = response.body().string();
                        JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                        if (!returnData.get("code").toString().equals("200")) {
                            Toast.makeText(getContext(), "服务端错误~", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            Toast.makeText(getContext(), "已取消订阅~", Toast.LENGTH_SHORT).show();
                            getDepartmentList();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } else {
            //订阅
            Retrofit retrofit = new Retrofit.Builder().baseUrl(Config.serverUrl).build();
            UploadService uploadService = retrofit.create(UploadService.class);
            Call<ResponseBody> call = uploadService.subscribe(Config.getInstance().getUserId(), temp.department_id);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    String result = null;
                    try {
                        result = response.body().string();
                        JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                        if (!returnData.get("code").toString().equals("200")) {
                            Toast.makeText(getContext(), "服务端错误~", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            Toast.makeText(getContext(), "订阅成功！", Toast.LENGTH_SHORT).show();
                            getDepartmentList();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        }
        super.onListItemClick(l, v, position, id);
    }

    //对数据进行加载
    private List<? extends Map<String, ?>> getData(ArrayList<SubscribeItem> apartmentList) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (SubscribeItem item : apartmentList) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("avatar", item.avatar);
            map.put("department", item.department);
            map.put("right_icon", item.isSubScribe ? R.drawable.cancel_subscribe : R.drawable.get_subscribe);
            list.add(map);
        }
        return list;
    }
}